package com.elite;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jcifs.Config;
import jcifs.UniAddress;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchResults;

public class LdapLoginServlet extends HttpServlet{
	private static final Log log=LogFactory.getLog(LdapLoginServlet.class);
	private String IP="";
	private int port=0;
	public void init(){
		IP=this.getInitParameter("IP");
		String port1=this.getInitParameter("PORT");
		port=Integer.parseInt(port1);
		log.info("LdapLoginServlet_ip:"+IP);
		log.info("LdapLoginServlet_port1:"+port1);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doPost(request,  response);
	}
	public PasswordAuthentication getPasswordAuthentication(String username,String password){
		try{
			String usernamewithdomain="10.1.32.16"+"/"+username;
			log.info("usernamewithdomain:"+usernamewithdomain);
			log.info("password:"+password);
			return (new PasswordAuthentication(usernamewithdomain,password.toCharArray()));
		}catch(Exception e){
			log.error("getPasswordAuthentication过程异常:"+getERRO(e)); 
			return null;
		}

	}
//	public void main1(String user,String password) throws Exception {
//        // Normally set this outside application.
//        // Note that as a side effect due to the way handlers are located,
//        // you can also achieve this by simply doing:
//        Config.registerSmbURLHandler();
//        // which we already do to register the smb handler.
//        //String pkgs = System.getProperty("java.protocol.handler.pkgs");
//        //pkgs = (pkgs != null) ? "jcifs|" + pkgs : "jcifs";
//        //System.setProperty("java.protocol.handler.pkgs", pkgs);
//        //
////        String location = args[0];
//        String domain ="10.1.32.16";
//        // can also specify these in the URL, i.e.
//        //     http://DOMAIN%5cuser:password@host/dir/file.html
//        // which will override these properties
//        Config.setProperty("jcifs.smb.client.domain", domain);
//        Config.setProperty("jcifs.smb.client.username", user);
//        Config.setProperty("jcifs.smb.client.password", password);
//
//        try {
//            Config.setProperty("jcifs.netbios.hostname",
//                    Config.getProperty("jcifs.netbios.hostname",
//                            InetAddress.getLocalHost().getHostName()));
//        }catch (Exception ex){
//        	log.error("main1过程异常:"+getERRO(ex)); 
//        }
//        URL url = new URL(location);
//        BufferedReader reader = new BufferedReader(
//                new InputStreamReader(url.openStream()));
//        String line;
//        while ((line = reader.readLine()) != null) {
//           log.info(line);
//        }
//    }
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		try{
			request.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    PrintWriter out=response.getWriter();
			String userName=request.getParameter("username");
			String password=request.getParameter("password");
			log.info("userName:"+userName);
			log.info("password:"+password);
			log.info("IP:"+IP);
			UniAddress mydomaincontroller=UniAddress.getByName(IP);
			NtlmPasswordAuthentication mycreds=new NtlmPasswordAuthentication(IP,userName,password);
			try {
			    SmbSession.logon(mydomaincontroller,mycreds);
			    log.info("success");		    
			}catch(Exception e){
				log.info("登录失败:"+getERRO(e));
				out.print(0);
				return;
			}
			out.print(1);
		}catch(Exception e){
			log.info("doPost:"+getERRO(e));
		}


		
		
//		String username=request.getParameter("username");
//		String password=request.getParameter("password");
//		try{
//			
//		}catch(Exception e){
//			log.error("doPost过程异常:"+getERRO(e)); 
//		}
//		PasswordAuthentication a=getPasswordAuthentication(username,password);
//		log.info("a.getPassword():"+a.getPassword());
//		log.info("a.getUserName():"+a.getUserName());
		
		
		
		
//		int resulut=0;
//		request.setCharacterEncoding("UTF-8");
//	    response.setContentType("text/html;charset=UTF-8");
//	    PrintWriter out=response.getWriter();
//		try{
//			String username=request.getParameter("username");
//			String password=request.getParameter("password");
//			log.info("username:"+username+"-----password:"+password);
//			LDAPConnection lc = new LDAPConnection(); 
//			lc.connect(IP,port); 
//			try{
//				lc.bind(LDAPConnection.LDAP_V3,username,password);  
//		        LDAPSearchConstraints constraints=new LDAPSearchConstraints();
////		        log.info("constraints.getMaxResults():"+constraints.getMaxResults());
//		        constraints.setMaxResults(3000);  
//				LDAPSearchResults rs=lc.search("CN=李恺,OU=客户服务部,OU=总公司部门,DC=hlic,DC=cn",LDAPConnection.SCOPE_SUB,"(&(objectcategory=user))",null,false, constraints);
//				while(rs.hasMore()){   
//		               LDAPEntry entry = rs.next();  
//		               log.info(entry.getAttributeSet()); 
//		               log.info(entry.getDN());  
//		               
//		           }  
//			}catch(Exception e){
//				log.error("LDAP登录过程异常:"+getERRO(e)); 
//				resulut=0;
//				out.print(resulut);
//				return;
//			}
//			resulut=1;
//			out.print(resulut);
//		}catch(Exception e){
//			log.error("doPost过程异常:"+getERRO(e));   
//			resulut=0;
//			out.print(resulut);
//			return;
//		}
		
	}
	private String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}      
}
